package com.kaifamiao.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.logging.Logger;

public class EncodingFilter implements Filter {

    private static final String DEFAULT_CHARSET_NAME = "UTF-8" ;
    private static final String CHARSET_PARAM_NAME = "charset" ;

    private Logger logger = Logger.getLogger( this.getClass().getName() );

    private String charsetName ;

    @Override
    public void init(FilterConfig config) throws ServletException {
        logger.info( "初始化" );
        charsetName = config.getInitParameter( CHARSET_PARAM_NAME );
        charsetName = charsetName == null || charsetName.trim().isEmpty() ? DEFAULT_CHARSET_NAME : charsetName.trim();
        charsetName = Charset.isSupported( charsetName ) ? charsetName : DEFAULT_CHARSET_NAME ;
        logger.info( "通过初始化参数获取的字符编码名称是 " + charsetName );
    }

    @Override
    public void doFilter(ServletRequest req , ServletResponse resp , FilterChain chain )
            throws IOException, ServletException {
        req.setCharacterEncoding( charsetName );
        resp.setCharacterEncoding( charsetName );

        HttpServletRequest request = (HttpServletRequest) req ;
        String uri = request.getRequestURI();
        DispatcherType type = request.getDispatcherType();
        logger.info( "正在请求:" + uri + " , dispatch type: " + type );

        // 通过过滤器链(FilterChain)向后传递 请求 和 响应
        chain.doFilter( req , resp );

        logger.info( "被请求的资源: " + uri + " 已经返回" );
    }

    @Override
    public void destroy() {
        logger.info( "销毁" );
    }
}
